#include "eeprom.h"

void eeprom_init(){
	//nothing to init when using EEPROM
}

void eeprom_writebyte(unsigned int uiAddress, unsigned char ucData){
	while(EECR & _BV(EEWE)); 	//Wait for completion of previous write
	EEAR = uiAddress;			//Set up address and data registers
	EEDR = ucData;
	SREG = SREG & DISABLE_INT;			//disable interrup

	asm volatile("sbi %0,%1" :: "I" (_SFR_IO_ADDR(EECR)) , "I" (2));
	asm volatile("sbi %0,%1" :: "I" (_SFR_IO_ADDR(EECR)) , "I" (1));

	SREG = SREG | ENABLE_INT;			//re-enable interrupt
}

void eeprom_writestr(unsigned int uiAddress_start, unsigned char *ucData_buff, unsigned char ucData_len){
	unsigned char i__;
	if(!ucData_buff)return;
	for(i__=0;i__<ucData_len;i__++){
		eeprom_writebyte(uiAddress_start + i__, ucData_buff[i__]);
	}
}

unsigned char eeprom_readbyte(unsigned int uiAddress){
	while(EECR & _BV(EEWE)); 	//Wait for completion of previous write
	SREG = SREG & 0x7f;			//disable interrup
	EEAR = uiAddress;			//Set up address register
	EECR |= _BV(EERE);			//Start eeprom read by writing EERE
	SREG = SREG | 0x80;			//re-enable interrupt
	return EEDR;				//Return data from data register
}

void eeprom_readstr(unsigned int uiAddress_start, unsigned char *ucData_buff, unsigned char ucData_len){
	unsigned char i__;
	if(!ucData_buff)
		ucData_buff = malloc(ucData_len);
	if(!ucData_buff)return;
	for(i__=0;i__<ucData_len;i__++){
		*ucData_buff++ = eeprom_readbyte(uiAddress_start + i__);
	}
}
